package com.lancoo.cvas.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lancoo.cvas.entity.*;
import com.lancoo.cvas.mapper.*;
import com.lancoo.cvas.pojo.common.Deleted;
import com.lancoo.cvas.pojo.common.IsEnable;
import com.lancoo.cvas.pojo.vo.*;
import com.lancoo.cvas.service.*;
import com.lancoo.cvas.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


@Service("courseService")
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {


    @Resource
    private CourseMapper courseMapper;

    @Resource
    private SegmentService segmentService;

    @Resource
    private SegmentMapper segmentMapper;

    @Resource
    private PlanTeachingCourseSegmentMapper planTeachingCourseSegmentMapper;

    @Resource
    private PlanTeachingService planTeachingService;

    @Resource
    private CourseWeekService courseWeekService;

    @Resource
    private SegmentWeekService segmentWeekService;

    @Resource
    private TeachingClassWeekService teachingClassWeekService;


    @Resource
    private ClassInfoMapper classInfoMapper;

    @Resource
    private PlanTeachingStudentMapper planTeachingStudentMapper;

    @Resource
    private CourseService courseService;
    @Resource
    private ClassCourseCloseService classCourseCloseService;
    @Resource
    private ClassCourseCloseMapper classCourseCloseMapper;

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ClassRoomService classRoomService;
    @Resource
    private StudentMapper studentMapper;


    @Override
    public void syncCourse(Integer taskId, Set<Course> courses) {

        List<Course> insertList = new ArrayList<>();
        List<String> courseList = courseMapper.selectBaseCourseIds(taskId, Deleted.NOT.getCode());
        for (Course course : courses) {
            if (!courseList.contains(course.getBaseCourseId())) {
                insertList.add(course);
            }
        }

        if (CollUtil.isNotEmpty(insertList)) {
            courseMapper.addBatch(insertList);
        }

    }

    @Override
    public void syncSegment(Integer taskId, Set<Segment> syncSegment) {

        List<Segment> insertList = new ArrayList<>();
        List<String> segmentList = segmentMapper.selectBaseSegmentIds(taskId, Deleted.NOT.getCode());
        for (Segment segment : syncSegment) {
            if (!segmentList.contains(segment.getBaseSegmentId())) {
                insertList.add(segment);
            }
        }

        if (CollUtil.isNotEmpty(insertList)) {
            segmentMapper.addBatch(insertList);
        }
    }

    @Override
    public List<AddCourseSegment> getNotEnableCourseList(Integer taskId, String baseTeachingPlanId, String courseTypeId, String classId, Integer courseNature, String keyWord) {
        //获取未启用课程，可用来进行课程新增

        List<AddCourseSegment> resultList = new ArrayList<>();

        List<Course> list = courseMapper.getNotIsEnableCourse(taskId, courseTypeId, courseNature, keyWord);


        List<PlanTeachingCourseSegment> planTeachingCourseSegmentList = planTeachingCourseSegmentMapper
                .selectList(new LambdaQueryWrapper<PlanTeachingCourseSegment>()
                        .eq(PlanTeachingCourseSegment::getTaskId,taskId)
                        .eq(PlanTeachingCourseSegment::getBaseTeachingPlanId, baseTeachingPlanId)
                        .eq(PlanTeachingCourseSegment::getDeleted, Deleted.NOT.getCode())
                        .eq(PlanTeachingCourseSegment::getFlag, 1));


        List<String> courseIds = planTeachingCourseSegmentList.stream()
                .map(PlanTeachingCourseSegment::getBaseCourseId)
                .collect(Collectors.toList());

        List<Course> courses = list.stream().filter(p -> !courseIds.contains(p.getBaseCourseId())).collect(Collectors.toList());


        courses.forEach(course -> {
            StringBuilder string = new StringBuilder();
            string.append(course.getCourseName()).append("(").append(course.getCourseCode()).append(")-")
                    .append(course.getCourseType()).append("-").append(course.getCourseNature().equals(1) ? "必修" : "选修");
            resultList.add(AddCourseSegment.builder().id(course.getCourseId()).name(string.toString()).baseId(course.getBaseCourseId()).build());
        });
        return resultList;
    }

    @Override
    public List<AddCourseSegment> getNotEnableSegmentList(Integer taskId, String baseTeachingPlanId, String classId, String segmentTypeId, String keyWord) {

        //获取未启用环节，用于环节新增
        List<AddCourseSegment> resultList = new ArrayList<>();

        List<Segment> list = segmentMapper.getNotIsEnableSegment(taskId, segmentTypeId, keyWord);

        List<PlanTeachingCourseSegment> planTeachingCourseSegmentList = planTeachingCourseSegmentMapper.selectList(new LambdaQueryWrapper<PlanTeachingCourseSegment>()
                .eq(PlanTeachingCourseSegment::getBaseTeachingPlanId, baseTeachingPlanId)
                .eq(PlanTeachingCourseSegment::getTaskId,taskId)
                .eq(PlanTeachingCourseSegment::getDeleted, Deleted.NOT.getCode())
                .eq(PlanTeachingCourseSegment::getFlag, 2));

        List<String> segmentIds = planTeachingCourseSegmentList.stream()
                .map(PlanTeachingCourseSegment::getBaseCourseId).distinct()
                .collect(Collectors.toList());


        List<Segment> segments = list.stream().filter(p -> !segmentIds.contains(p.getBaseSegmentId())).collect(Collectors.toList());


        segments.forEach(segment -> {
            StringBuilder string = new StringBuilder();
            string.append(segment.getSegmentName()).append("(").append(segment.getSegmentCode()).append(")-")
                    .append(segment.getSegmentType());
            resultList.add(AddCourseSegment.builder().id(segment.getSegmentId()).name(string.toString()).baseId(segment.getBaseSegmentId()).build());
        });
        return resultList;
    }

    @Override
    public void courseAdd(Integer taskId, String baseTeachingPlanId, String classId, String courseId, Integer flag, String reserve) {


        //新增课程，如果存在修改状态，反之新增课程
        PlanTeachingCourseSegment planTeachingCourseSegment1 = planTeachingCourseSegmentMapper
                .selectOne(new LambdaQueryWrapper<PlanTeachingCourseSegment>()
                .eq(PlanTeachingCourseSegment::getTaskId, taskId)
                .eq(PlanTeachingCourseSegment::getBaseTeachingPlanId, baseTeachingPlanId)
                .eq(PlanTeachingCourseSegment::getBaseCourseId, courseId)
                .eq(PlanTeachingCourseSegment::getFlag, flag));

        if (ObjUtil.isNotNull(planTeachingCourseSegment1)) {
            planTeachingCourseSegment1.setDeleted(Deleted.NOT.getCode());
            planTeachingCourseSegmentMapper.updateById(planTeachingCourseSegment1);
        } else {
            PlanTeachingCourseSegment planTeachingCourseSegment = new PlanTeachingCourseSegment();
            planTeachingCourseSegment.setTaskId(taskId)
                    .setBaseTeachingPlanId(baseTeachingPlanId)
                    .setBaseCourseId(courseId).setFlag(flag)
                    .setReserve(reserve);
            planTeachingCourseSegmentMapper.insert(planTeachingCourseSegment);
        }



    }

    @Override
    public void segmentAdd(Integer taskId, String baseTeachingPlanId, String segmentId, String classId, Integer flag, String reserve) {


       //新增环节 未启用修改 没有进行添加
        PlanTeachingCourseSegment planTeachingCourseSegment1 = planTeachingCourseSegmentMapper.selectOne(new LambdaQueryWrapper<PlanTeachingCourseSegment>()
                .eq(PlanTeachingCourseSegment::getBaseTeachingPlanId, baseTeachingPlanId).eq(PlanTeachingCourseSegment::getBaseCourseId, segmentId)
                .eq(PlanTeachingCourseSegment::getFlag, flag));
        if (ObjUtil.isNotNull(planTeachingCourseSegment1)) {
            planTeachingCourseSegment1.setDeleted(Deleted.NOT.getCode());
            planTeachingCourseSegmentMapper.updateById(planTeachingCourseSegment1);
        } else {
            PlanTeachingCourseSegment planTeachingCourseSegment = new PlanTeachingCourseSegment();
            planTeachingCourseSegment.setTaskId(taskId)
                    .setBaseTeachingPlanId(baseTeachingPlanId).setBaseCourseId(segmentId).setFlag(flag).setReserve(reserve);
            planTeachingCourseSegmentMapper.insert(planTeachingCourseSegment);
        }


    }

    /**
     * 关闭选中的课程列表
     *
     * @param courseIds
     * @param taskId
     * @return
     */
    @Override
    public Integer closeCourseList(ArrayList<String> courseIds, Integer taskId) {
        return planTeachingCourseSegmentMapper.update(null, new LambdaUpdateWrapper<PlanTeachingCourseSegment>()
                .eq(PlanTeachingCourseSegment::getTaskId, taskId).eq(PlanTeachingCourseSegment::getFlag, 1)
                .in(PlanTeachingCourseSegment::getBaseCourseId, courseIds).set(PlanTeachingCourseSegment::getDeleted, Deleted.YES.getCode()));
    }

    /**
     * 关闭选中的环节列表
     *
     * @param segmentIds
     * @param taskId
     * @return
     */
    @Override
    public Integer closeSegmentList(ArrayList<String> segmentIds, Integer taskId) {
        return planTeachingCourseSegmentMapper.update(null, new LambdaUpdateWrapper<PlanTeachingCourseSegment>()
                .eq(PlanTeachingCourseSegment::getTaskId, taskId).eq(PlanTeachingCourseSegment::getFlag, 2)
                .in(PlanTeachingCourseSegment::getBaseCourseId, segmentIds).set(PlanTeachingCourseSegment::getDeleted, Deleted.YES.getCode()));
    }

    @Override
    public void initTeachingClassWeek(List<TeachingClass> teachingClassList) {
        if (CollUtil.isNotEmpty(teachingClassList)) {
            //待新增教学班参数
            List<TeachingClassWeek> allTeachingClassWeeks = new ArrayList<>();
            TeachingClass teachingClass = teachingClassList.get(0);

            if (teachingClass.getFlag() == 1) {
                //课程
                List<CourseWeek> courseWeekList = courseWeekService.list(new LambdaQueryWrapper<CourseWeek>()
                        .eq(CourseWeek::getCourseId, teachingClass.getCourseId())
                        .eq(CourseWeek::getDeleted, Deleted.NOT.getCode()));
                if (CollUtil.isNotEmpty(courseWeekList)) {
                    CopyOptions.create().setIgnoreProperties("id");
                    teachingClassList.forEach(a -> {
                        List<TeachingClassWeek> teachingClassWeeks = BeanUtil.copyToList(courseWeekList, TeachingClassWeek.class, CopyOptions.create().setIgnoreProperties("id"));
                        teachingClassWeeks.forEach(b -> {
                            b.setTeachingClassId(a.getTeachingClassId());
                        });
                        allTeachingClassWeeks.addAll(teachingClassWeeks);
                    });
                }
            } else {
                //环节 按理说环节只有一条数据
                SegmentWeek segmentWeek = segmentWeekService.getOne(new LambdaQueryWrapper<SegmentWeek>()
                        .eq(SegmentWeek::getSegmentId, teachingClass.getCourseId())
                        .eq(SegmentWeek::getDeleted, Deleted.NOT.getCode()), false);
                if (ObjUtil.isNotNull(segmentWeek)) {
                    teachingClassList.forEach(a -> {
                        TeachingClassWeek teachingClassWeek = TeachingClassWeek.builder()
                                .teachingClassId(a.getTeachingClassId())
                                .week(segmentWeek.getWeek())
                                .hourType(0).build();
                        allTeachingClassWeeks.add(teachingClassWeek);
                    });
                }
            }
            teachingClassWeekService.saveBatch(allTeachingClassWeeks);
        }
    }

    /**
     * 获取课程环节类别
     *
     * @param taskId
     * @param flag
     * @return
     */
    @Override
    public List<CourseTypeDto> getCourseTypeByTaskId(Integer taskId, Integer flag) {
        List<CourseTypeDto> list = new ArrayList<>();
        if (flag.equals(1)) {
            list = courseMapper.getCourseTypeByTaskId(taskId);
        } else {
            list = segmentMapper.getSegmentTypeByTaskId(taskId);
        }
        return list;
    }

    @Override
    public List<Course> getCourseListByClass(Integer taskId, String classId, String baseTeachingPlanId) {

        //获取对应培养计划对应学生
        List<PlanTeachingToStudent> planTeachingToStudentList = planTeachingStudentMapper.selectPlanTeachingToStudentList(taskId, Deleted.NOT.getCode());

        //获取培养计划对应课程
        List<PlanTeachingCourseSegment> planTeachingCourseSegments = planTeachingCourseSegmentMapper.selectPlanTeachingCourseSegmentList(taskId, Deleted.NOT.getCode());

        //获取培养计划
        List<PlanTeaching> planTeachings = planTeachingService.lambdaQuery().eq(PlanTeaching::getTaskId, taskId)
                .eq(PlanTeaching::getDeleted, Deleted.NOT.getCode()).list();

        //通过行政班id筛选学生
        List<PlanTeachingToStudent> planTeachingToStudents = planTeachingToStudentList.stream()
                .filter(p -> p.getClassId().equals(classId)).collect(Collectors.toList());


        List<PlanTeaching> pTeaching = planTeachings.stream()
                .filter(p -> planTeachingToStudents.stream().anyMatch(o -> p.getBaseTeachingPlanId().equals(o.getBaseTeachingPlanId())))
                .collect(Collectors.toList());


        //获取对应课程
        List<Course> courses = courseMapper.getCourseList(taskId);


        Set<String> baseCourse = new HashSet<>();

        List<PlanTeachingCourseSegment> pTeachingCourseSegments = planTeachingCourseSegments.stream()
                .filter(p -> p.getBaseTeachingPlanId().equals(baseTeachingPlanId)
                        && p.getDeleted() == Deleted.NOT.getCode() && p.getFlag() == 1)
                .collect(Collectors.toList());


        if (CollUtil.isNotEmpty(pTeachingCourseSegments)) {
            for (PlanTeachingCourseSegment pTeachingCourseSegment : pTeachingCourseSegments) {


                if (!baseCourse.contains(pTeachingCourseSegment.getBaseCourseId())) {
                    baseCourse.add(pTeachingCourseSegment.getBaseCourseId());
                }

            }
        }



        //判断课程是否被启用
        List<Course> courseList = new ArrayList<>();
        if (CollUtil.isNotEmpty(baseCourse)) {
            for (String c : baseCourse) {
                List<Course> coursesCount = courses.stream()
                        .filter(p -> p.getBaseCourseId().equals(c))
                        .collect(Collectors.toList());
                courseList.addAll(coursesCount);
            }
        }


        //获取未启用课程
        List<ClassCourseClose> classCourseCloses = classCourseCloseService.lambdaQuery()
                .eq(ClassCourseClose::getTaskId, taskId)
                .eq(ClassCourseClose::getClassId, classId)
                .eq(ClassCourseClose::getBaseTeachingPlanId, baseTeachingPlanId)
                .eq(ClassCourseClose::getFlag, 1)
                .eq(ClassCourseClose::getDeleted, Deleted.YES.getCode()).list();

        List<Long> courseIds = classCourseCloses.stream().map(ClassCourseClose::getCourseId).distinct().collect(Collectors.toList());

        List<Course> courseUnEnable = courseList.stream().filter(p -> courseIds.contains(p.getCourseId())).collect(Collectors.toList());

        courseList.removeAll(courseUnEnable);

        courseUnEnable.forEach(o -> {
            o.setIsEnable(IsEnable.UNABLE.getCode());
        });

        courseList.addAll(courseUnEnable);


        List<Course> collect = courseList.stream().sorted(Comparator.comparing(Course::getCourseId)).collect(Collectors.toList());

        return collect;
    }

    @Override
    public List<Course> getCourseListByMajor(Integer taskId, String gradeId, Long majorId, String baseTeachingPlanId) {

        //获取培养方案对应学生
        List<PlanTeachingToStudent> planTeachingToStudentList = planTeachingStudentMapper.selectPlanTeachingToStudentList(taskId, Deleted.NOT.getCode());

        //筛选获取对应行政班
        List<ClassInfo> classInfos = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>()
                .eq(ClassInfo::getTaskId, taskId)
                .like(ClassInfo::getMajorId, majorId)
                .eq(ClassInfo::getGradeId, gradeId));


        //获取对应学生
        List<Course> courses = courseService.lambdaQuery()
                .eq(Course::getTaskId, taskId)
                .eq(Course::getIsEnable, IsEnable.ENABLE.getCode())
                .eq(Course::getDeleted, Deleted.NOT.getCode())
                .list();

        //获取培养方案对应课程
        List<PlanTeachingCourseSegment> planTeachingCourseSegments = planTeachingCourseSegmentMapper.selectPlanTeachingCourseSegmentList(taskId, Deleted.NOT.getCode());


        List<String> classIds = classInfos.stream().map(ClassInfo::getClassId).distinct().collect(Collectors.toList());

        List<PlanTeachingToStudent> planTeachingToStudents = planTeachingToStudentList.stream()
                .filter(p -> classIds.contains(p.getClassId())).collect(Collectors.toList());


        List<PlanTeachingToStudent> planTeachingToStudents1 = planTeachingToStudents.stream().filter(p -> p.getBaseTeachingPlanId().equals(baseTeachingPlanId)).collect(Collectors.toList());

        List<String> collect1 = planTeachingToStudents1.stream().map(PlanTeachingToStudent::getClassId).distinct().collect(Collectors.toList());


        //获取未启用课程
        List<ClassCourseClose> classCourseCloseList = classCourseCloseService.lambdaQuery().eq(ClassCourseClose::getTaskId, taskId)
                .eq(ClassCourseClose::getGradeId, gradeId)
                .eq(ClassCourseClose::getFlag, 1)
                .eq(ClassCourseClose::getBaseTeachingPlanId, baseTeachingPlanId)
                .eq(ClassCourseClose::getDeleted, Deleted.YES.getCode()).list();

        Set<String> baseCourse = new HashSet<>();
        List<PlanTeachingCourseSegment> pTeachingCourseSegments = planTeachingCourseSegments.stream()
                .filter(p -> p.getBaseTeachingPlanId().equals(baseTeachingPlanId)
                        && p.getFlag() == 1).collect(Collectors.toList());


        if (CollUtil.isNotEmpty(pTeachingCourseSegments)) {
            for (PlanTeachingCourseSegment pTeachingCourseSegment : pTeachingCourseSegments) {
                if (!baseCourse.contains(pTeachingCourseSegment.getBaseCourseId())) {
                    baseCourse.add(pTeachingCourseSegment.getBaseCourseId());
                }
            }
        }


        //判断课程是否被启用
        List<Course> courseList = new ArrayList<>();
        if (CollUtil.isNotEmpty(baseCourse)) {
            for (String c : baseCourse) {
                List<Course> coursesCount = courses.stream()
                        .filter(p -> p.getBaseCourseId().equals(c))
                        .collect(Collectors.toList());
                courseList.addAll(coursesCount);
            }
        }


        List<PlanTeachingCourseSegment> collect2 = planTeachingCourseSegments.stream()
                .filter(p -> p.getBaseTeachingPlanId().equals(baseTeachingPlanId)).collect(Collectors.toList());

        Map<Long, List<ClassCourseClose>> closeMap = classCourseCloseList.stream()
                .collect(Collectors.groupingBy(ClassCourseClose::getCourseId));

        //如果培养方案应用班级等于未启用班级则未启用，反之启用
        Integer classNum = collect1.size();
        List<Long> deletedCourseIds = new ArrayList<>();
        closeMap.forEach((o, v) -> {
            if (v.size() == classNum) {
                deletedCourseIds.add(o);
            }
        });
        List<Course> deletedCourse = courseList.stream().filter(p -> deletedCourseIds.stream().anyMatch(o -> o.equals(p.getCourseId()))).collect(Collectors.toList());

        courseList.removeAll(deletedCourse);

        deletedCourse.forEach(o -> {
            o.setIsEnable(IsEnable.UNABLE.getCode());
        });

        courseList.addAll(deletedCourse);

        //返回对应课程信息
        List<Course> collect = courseList.stream().sorted(Comparator.comparing(Course::getCourseId)).collect(Collectors.toList());

        return collect;
    }

    @Override
    public List<CourseTypeDto> getCourseType(Integer taskId, Integer flag) {
        List<CourseTypeDto> courseTypeDtoList = new ArrayList<>();
        //获取课程类别

        //获取课程类别
        if (flag == 1) {
            List<Course> courseList = courseMapper.selectList(new LambdaQueryWrapper<Course>().eq(Course::getTaskId, taskId)
                    .eq(Course::getDeleted, Deleted.NOT.getCode()));

            Map<String, String> courseTypeMap = courseList.stream().collect(Collectors.toMap(Course::getCourseTypeId, Course::getCourseType, (o1, o2) -> o1));

            courseTypeMap.forEach((key, value) -> {
                CourseTypeDto courseTypeDto = new CourseTypeDto();
                courseTypeDto.setTypeId(key);
                courseTypeDto.setTypeName(value);
                courseTypeDtoList.add(courseTypeDto);
            });

            //获取环节类别
        } else if (flag == 2) {
            List<Segment> segmentList = segmentMapper.selectList(new LambdaQueryWrapper<Segment>().eq(Segment::getTaskId, taskId)
                    .eq(Segment::getDeleted, Deleted.NOT.getCode()));

            Map<String, String> segmentTypeMap = segmentList.stream().collect(Collectors.toMap(Segment::getSegmentTypeId, Segment::getSegmentType, (o1, o2) -> o1));

            segmentTypeMap.forEach((key, value) -> {
                CourseTypeDto courseTypeDto = new CourseTypeDto();
                courseTypeDto.setTypeId(key);
                courseTypeDto.setTypeName(value);
                courseTypeDtoList.add(courseTypeDto);
            });
        }

        return courseTypeDtoList;
    }

    /**
     * 根据班级判断课程启用关闭
     *
     * @param courseIds
     * @param taskId
     * @return
     */
    @Override
    public Integer closeCourseListByClass(CloseCourseDTO closeCourseDTO) {

        //添加对应班级未启用课程信息，同时清除缓存
        ClassInfo classInfo = classInfoMapper.selectOne(new LambdaQueryWrapper<ClassInfo>()
                .eq(ClassInfo::getTaskId, closeCourseDTO.getTaskId())
                .eq(ClassInfo::getClassId, closeCourseDTO.getClassId()));

        List<ClassCourseClose> classCourseCloses = new ArrayList<>();
        if (classInfo != null) {
            List<CourseFlagDto> courseFlagDtoList = closeCourseDTO.getCourseFlagDtoList();
            courseFlagDtoList.forEach(o -> {
                ClassCourseClose classCourseClose = new ClassCourseClose();
                classCourseClose.setTaskId(closeCourseDTO.getTaskId());
                classCourseClose.setClassId(closeCourseDTO.getClassId());
                classCourseClose.setCourseId(o.getCourseId());
                classCourseClose.setGradeId(classInfo.getGradeId());
                classCourseClose.setBaseTeachingPlanId(closeCourseDTO.getBaseTeachingPlanId());
                classCourseClose.setFlag(1);
                classCourseClose.setDeleted(o.getFlag());
                classCourseCloses.add(classCourseClose);
            });
            classCourseCloseMapper.saveOrUpdateBatch(classCourseCloses);
        }

        redisUtil.del("cvas:com.lancoo.cvas.mapper.ClassCourseCloseMapper");

        return classCourseCloses.size();

    }

    @Override
    public Integer closeSegmentListByClass(CloseSegmentDTO closeSegmentDTO) {

        //添加未启用环节信息，同时清除缓存
        ClassInfo classInfo = classInfoMapper.selectOne(new LambdaQueryWrapper<ClassInfo>()
                .eq(ClassInfo::getTaskId, closeSegmentDTO.getTaskId())
                .eq(ClassInfo::getClassId, closeSegmentDTO.getClassId()));
        List<ClassCourseClose> classCourseCloses = new ArrayList<>();
        if (classInfo != null) {
            List<CourseFlagDto> courseFlagDtoList = closeSegmentDTO.getCourseFlagDtoList();
            courseFlagDtoList.forEach(o -> {
                ClassCourseClose classCourseClose = new ClassCourseClose();
                classCourseClose.setTaskId(closeSegmentDTO.getTaskId());
                classCourseClose.setClassId(closeSegmentDTO.getClassId());
                classCourseClose.setGradeId(classInfo.getGradeId());
                classCourseClose.setCourseId(o.getCourseId());
                classCourseClose.setBaseTeachingPlanId(closeSegmentDTO.getBaseTeachingPlanId());
                classCourseClose.setFlag(2);
                classCourseClose.setDeleted(o.getFlag());
                classCourseCloses.add(classCourseClose);
            });
            classCourseCloseMapper.saveOrUpdateBatch(classCourseCloses);
        }

        redisUtil.del("cvas:com.lancoo.cvas.mapper.ClassCourseCloseMapper");
        return classCourseCloses.size();
    }

    @Override
    public List<AddCourseSegment> getNotEnableCourseListByMajor(Integer taskId, String baseTeachingPlanId, String courseTypeId, String gradeId, Long majorId, Integer courseNature, String keyWord) {

        //获取对应班级
        List<ClassInfo> classInfoList = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>().eq(ClassInfo::getTaskId, taskId).eq(ClassInfo::getGradeId, gradeId)
                .eq(ClassInfo::getMajorId, majorId));

        List<AddCourseSegment> result = new ArrayList<>();
        //获取班级未启用课程
        classInfoList.forEach(o -> {
            List<AddCourseSegment> notEnableCourseList = getNotEnableCourseList(taskId, baseTeachingPlanId, courseTypeId, o.getClassId(), courseNature, keyWord);
            result.addAll(notEnableCourseList);
        });

        List<AddCourseSegment> collect = result.stream().distinct().collect(Collectors.toList());

        return collect;
    }

    @Override
    public List<AddCourseSegment> getNotEnableSegmentListByMajor(Integer taskId, String baseTeachingPlanId, String gradeId, Long majorId, String segmentTypeId, String keyWord) {

        //获取对应班级,获取对应行政班
        List<ClassInfo> classInfoList = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>().eq(ClassInfo::getTaskId, taskId).eq(ClassInfo::getGradeId, gradeId)
                .eq(ClassInfo::getMajorId, majorId));

        List<AddCourseSegment> result = new ArrayList<>();
        classInfoList.forEach(o -> {
            List<AddCourseSegment> notEnableCourseList = getNotEnableSegmentList(taskId, baseTeachingPlanId, o.getClassId(), segmentTypeId, keyWord);
            result.addAll(notEnableCourseList);
        });

        List<AddCourseSegment> collect = result.stream().distinct().collect(Collectors.toList());
        return collect;
    }

    @Override
    public void courseAddByMajor(Integer taskId, String baseTeachingPlanId, String gradeId, Long majorId, String courseId, Integer flag, String reserve) {

        //获取专业有多少班级，获取对应培养方案进行添加课程
        List<ClassInfo> classInfoList = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>().eq(ClassInfo::getTaskId, taskId).eq(ClassInfo::getGradeId, gradeId)
                .eq(ClassInfo::getMajorId, majorId));

        classInfoList.forEach(o -> {
            courseAdd(taskId, baseTeachingPlanId, o.getClassId(), courseId, flag, reserve);
        });
    }

    @Override
    public void segmentAddByMajor(Integer taskId, String baseTeachingPlanId, String segmentId, String gradeId, Long majorId, Integer flag, String reserve) {

        //通过培养方案，专业获取班级，进行添加
        List<ClassInfo> classInfoList = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>().eq(ClassInfo::getTaskId, taskId).eq(ClassInfo::getGradeId, gradeId)
                .eq(ClassInfo::getMajorId, majorId));
        classInfoList.forEach(o -> {
            segmentAdd(taskId, baseTeachingPlanId, segmentId, o.getClassId(), flag, reserve);
        });
    }

    @Override
    public Integer closeCourseListByMajor(CloseCourseDTOByMajor closeCourseDTO) {
        //通过年级专业获取对应课程信息
        List<ClassInfo> classInfoList = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>().eq(ClassInfo::getTaskId, closeCourseDTO.getTaskId())
                .eq(ClassInfo::getGradeId, closeCourseDTO.getGradeId())
                .eq(ClassInfo::getMajorId, closeCourseDTO.getMajorId()));
        AtomicReference<Integer> ret = new AtomicReference<>(0);

        //添加未启用课程信息
        classInfoList.forEach(o -> {
            CloseCourseDTO closeCourseDTO1 = new CloseCourseDTO();
            closeCourseDTO1.setClassId(o.getClassId());
            closeCourseDTO1.setTaskId(closeCourseDTO.getTaskId());
            closeCourseDTO1.setCourseFlagDtoList(closeCourseDTO.getCourseFlagDtoList());
            closeCourseDTO1.setBaseTeachingPlanId(closeCourseDTO.getBaseTeachingPlanId());
            Integer integer = closeCourseListByClass(closeCourseDTO1);
            ret.updateAndGet(v -> v + integer);
        });
        return ret.get();
    }

    @Override
    public Integer closeSegmentListByMajor(CloseSegmentDTOByMajor closeSegmentDTO) {

        //通过专业年级获取对应班级
        List<ClassInfo> classInfoList = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>().eq(ClassInfo::getTaskId, closeSegmentDTO.getTaskId())
                .eq(ClassInfo::getGradeId, closeSegmentDTO.getGradeId())
                .eq(ClassInfo::getMajorId, closeSegmentDTO.getMajorId()));
        AtomicReference<Integer> ret = new AtomicReference<>(0);

        //对班级未启用环节进行添加
        classInfoList.forEach(o -> {
            CloseSegmentDTO closeSegmentDTO1 = new CloseSegmentDTO();
            closeSegmentDTO1.setTaskId(closeSegmentDTO.getTaskId());
            closeSegmentDTO1.setClassId(o.getClassId());
            closeSegmentDTO1.setCourseFlagDtoList(closeSegmentDTO.courseFlagDtoList);
            closeSegmentDTO1.setBaseTeachingPlanId(closeSegmentDTO.getBaseTeachingPlanId());
            Integer integer = closeSegmentListByClass(closeSegmentDTO1);
            ret.updateAndGet(v -> v + integer);
        });
        return ret.get();
    }

    @Override
    public String checkRoom(Integer taskId, Long roomId) {

        //检查教室是否被占用
        List<ClassRoom> classRoomList = classRoomService.lambdaQuery().eq(ClassRoom::getTaskId, taskId).eq(ClassRoom::getRoomId, roomId).list();
        if (CollUtil.isNotEmpty(classRoomList)) {
            ClassRoom classRoom = classRoomList.get(0);
            List<ClassInfo> classInfoList = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>().eq(ClassInfo::getTaskId, taskId).eq(ClassInfo::getId, classRoom.getClassId()));

            if (CollUtil.isNotEmpty(classInfoList)) {
                ClassInfo classInfo = classInfoList.get(0);

                return "该教室已被" + classInfo.getClassName() + "占据";
            }

            return "不存在该行政班";
        }
        return "该教室没有设置";
    }

    @Override
    public List<Course> getAllCourse(Integer taskId) {
        return courseService.lambdaQuery()
                .eq(Course::getTaskId, taskId)
                .eq(Course::getDeleted, Deleted.NOT.getCode())
                .list();
    }

//    @Override
//    public Integer openCourseListByClass(String classId, ArrayList<Long> courseIds, Integer taskId) {
//
//        ClassInfo classInfo = classInfoMapper.selectOne(new LambdaQueryWrapper<ClassInfo>()
//                .eq(ClassInfo::getTaskId, taskId)
//                .eq(ClassInfo::getClassId, classId));
//
//        if (classInfo != null) {
//            List<ClassCourseClose> classCourseCloses = new ArrayList<>();
//            courseIds.forEach(o -> {
//                ClassCourseClose classCourseClose = new ClassCourseClose();
//                classCourseClose.setTaskId(taskId);
//                classCourseClose.setClassId(classId);
//                classCourseClose.setCourseId(o);
//                classCourseClose.setGradeId(classInfo.getGradeId());
//                classCourseClose.setMajorId(classInfo.getMajorId());
//                classCourseClose.setFlag(1);
//                classCourseClose.setDeleted(Deleted.YES.getCode());
//                classCourseCloses.add(classCourseClose);
//            });
//            classCourseCloseMapper.saveOrUpdateBatch(classCourseCloses);
//        }
//
//        redisUtil.del("cvas:com.lancoo.cvas.mapper.ClassCourseCloseMapper");
//
//        return courseIds.size();
//    }
}